<?php

namespace IDock\Insurance\LIHI\Response;

use IDock\Http\Response;
use IDock\Insurance\LIHI\Response\AllLIHIResponse;
use IDock\Printer\EPolicyDownloadPrinter;

class EPolicyDownloadResponse extends AllLIHIResponse
{

    public function resolve(): Response
    {
        $body = $this->getBody();
        if (!json_decode($body)) {
            $this->setError('返回数据异常');
            return  $this;
        }
        $data = json_decode($body,true);

        if ($this->printer and  is_string($this->printer)) {
            $this->printer = new $this->printer;
        }

        $status = $data['status'] ?? '';

        if(!$status) {
            $this->setError('下载电子保单失败');
            return $this;
        }
        $this->setBody($data);

        return $this;
    }

    /**
     * @var EPolicyDownloadPrinter $printer
     */
    public $printer = EPolicyDownloadPrinter::class;


    public function printerInit(): Response
    {
        $body = $this->getBody();

        if ($this->printer) {
            $this->printer = new $this->printer;
        }

        $this->printer->finish = true;
        $this->printer->data = $body['pdfFileByte'] ?? '';
        $this->printer->url = $body['fileName'] ?? '';
        if(empty($this->printer->data) && empty($this->printer->url)){
            $this->setError('下载电子保单失败');
            return $this;
        }

        if($this->printer->data and !$this->checkIsPdf(base64_decode($this->printer->data))){
            $this->setError("获取电子保单链接失败，解释文件失败");
            return $this;
        }
        return $this;
    }

    private function checkIsPdf($file)
    {
        return substr($file,'0',4) == '%PDF';
    }
}
